import React, { Component } from 'react';

// 引入action
import { incrementAsync, increment, decrement } from '../../redux/actions/count';

// 引入connect用户连接UI组件和redux
import { connect } from 'react-redux';

class CountUI extends Component {
    increment = () => {
        const { value } = this.selectNumber;
        // store.dispatch(createIncrementAction(value));
        this.props.increment(value * 1);
    };

    decrement = () => {
        const { value } = this.selectNumber;

        this.props.decrement(value * 1);
    };

    incrementIfOld = () => {
        const { value } = this.selectNumber;
        const count = this.props.count;
        console.log('incrementIfOld', count, count % 2 !== 0);
        if (count % 2 !== 0) {
            this.props.increment(value * 1);
        }
    };

    incrementAsync = () => {
        const { value } = this.selectNumber;
        this.props.incrementAsync(value * 1, 500);
    };

    render() {
        //  console.log('UI组件接收到的props是', this.props);
        return (
            <div>
                <h2>我是Count组件</h2>
                <h4>
                    当前求和为：{this.props.count}，下方组件人人数为：{this.props.peronCount}
                </h4>
                <select ref={c => (this.selectNumber = c)}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>
                &nbsp;
                <button onClick={this.increment}>+</button>&nbsp;
                <button onClick={this.decrement}>-</button>&nbsp;
                <button onClick={this.incrementIfOld}>当前求和为奇数再加</button>&nbsp;
                <button onClick={this.incrementAsync}>异步加</button>&nbsp;
            </div>
        );
    }
}

// a函数的返回值作为状态传递给了UI组件
// const mapStateToProps = state => ({ count: state });

// b函数的返回值是操作状态的方法
// const mapDispatchToProps = dispatch => ({
//     jia: number => dispatch(createIncrementAction(number)),
//     jian: number => dispatch(createDecrementAction(number)),
//     jianAsync: (number, time) => dispatch(createIncrementAsyncAction(number, time)),
// });

// export default connect(mapStateToProps, mapDispatchToProps)(CountUI);
export default connect(
    state => ({ count: state.count, peronCount: state.persons.length }),
    // mapDispatchToProps的简写
    {
        increment,
        decrement,
        incrementAsync,
    }
    // mapDispatchToProps的一般写法
    /* dispatch => ({
        jia: number => dispatch(createIncrementAction(number)),
        jian: number => dispatch(createDecrementAction(number)),
        jianAsync: (number, time) => dispatch(createIncrementAsyncAction(number, time)),
    }) */
)(CountUI);
